<template>

  <div class="payment-audit-page">
    <!-- 页面标题头部 -->
    <div class="page-header">
      <div class="page-title">订单支付审核</div>
      <div class="page-subtitle">买家上传支付截图后，在此完成确认或拒绝操作</div>
    </div>
    <!-- 统计卡片 -->
    <div class="stats-cards" :key="renderKey">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card 
            class="stats-card" 
            :class="{ 'stats-card-active': searchForm.status === 'pending' }"
            @click.native="handleStatsCardClick('pending')"
          >
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.pending }}</div>
              <div class="stats-label">待审核</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card 
            class="stats-card" 
            :class="{ 'stats-card-active': searchForm.status === 'confirmed' }"
            @click.native="handleStatsCardClick('confirmed')"
          >
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.confirmed }}</div>
              <div class="stats-label">已确认</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card 
            class="stats-card" 
            :class="{ 'stats-card-active': searchForm.status === 'rejected' }"
            @click.native="handleStatsCardClick('rejected')"
          >
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.rejected }}</div>
              <div class="stats-label">已拒绝</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card 
            class="stats-card" 
            :class="{ 'stats-card-active': searchForm.status === '' }"
            @click.native="handleStatsCardClick('')"
          >
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.total }}</div>
              <div class="stats-label">总计</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable @change="handleStatusChange">
            <el-option label="全部" value=""></el-option>
            <el-option label="待确认" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="订单号/商品标题" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 当前筛选状态显示 -->
      <div class="filter-status" v-if="searchForm.status || searchForm.keyword">
        <el-tag 
          v-if="searchForm.status" 
          :type="getStatusTagType(searchForm.status)"
          closable
          @close="clearStatusFilter"
        >
          {{ getStatusText(searchForm.status) }}
        </el-tag>
        <el-tag 
          v-if="searchForm.keyword" 
          type="info"
          closable
          @close="clearKeywordFilter"
        >
          关键词: {{ searchForm.keyword }}
        </el-tag>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          支付审核列表
          <span class="order-count" v-if="searchForm.status">
            ({{ filteredOrderCount }}条)
          </span>
        </div>
        <div class="table-actions">
          <el-button 
            type="success" 
            @click="handleBatchConfirm" 
            :disabled="!selectedRows.length || !canBatchConfirm"
            v-if="canBatchConfirm"
          >
            批量确认
          </el-button>
          <el-button 
            type="danger" 
            @click="handleBatchReject" 
            :disabled="!selectedRows.length || !canBatchReject"
            v-if="canBatchReject"
          >
            批量拒绝
          </el-button>
          <el-button type="primary" @click="refreshData">刷新</el-button>
          <el-button type="warning" @click="forceRefresh">强制刷新</el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>

        <el-table-column label="买家信息" width="200">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar
                :src="getBuyerAvatar(scope.row)"
                size="small"
                :icon="!getBuyerAvatar(scope.row) ? 'el-icon-user' : ''"
              ></el-avatar>
              <span class="user-name">{{ getBuyerNickname(scope.row) }}</span>
              <div style="font-size: 12px; color: #999;">ID: {{ getBuyerId(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="卖家信息" width="200">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar
                :src="getSellerAvatar(scope.row)"
                size="small"
                :icon="!getSellerAvatar(scope.row) ? 'el-icon-user' : ''"
              ></el-avatar>
              <span class="user-name">{{ getSellerNickname(scope.row) }}</span>
              <div style="font-size: 12px; color: #999;">ID: {{ getSellerId(scope.row) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商品信息" width="200">
          <template slot-scope="scope">
            <div class="product-info">
              <el-image
                v-if="getProductImage(scope.row)"
                :src="getProductImage(scope.row)"
                style="width: 40px; height: 40px; margin-right: 8px;"
                fit="cover"
              ></el-image>
              <div>
                <div class="product-title">{{ getProductTitle(scope.row) }}</div>
                <div style="font-size: 12px; color: #999;">
                  数量: {{ getProductCount(scope.row) }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="支付金额" width="120">
          <template slot-scope="scope">
            <div>
              <div class="price">¥{{ getPaymentAmount(scope.row) }}</div>
              <div v-if="getPayAmount(scope.row)" style="font-size: 12px; color: #999;">
                实付: ¥{{ getPayAmount(scope.row) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="支付截图" width="120">
          <template slot-scope="scope">
            <el-image
              v-if="getPaymentImage(scope.row)"
              :src="getPaymentImage(scope.row)"
              :preview-src-list="[getPaymentImage(scope.row)]"
              style="width: 60px; height: 60px"
              fit="cover"
            ></el-image>
            <span v-else style="color: #999;">无图片</span>
          </template>
        </el-table-column>

        <el-table-column label="支付状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getPaymentStatusType(getPaymentStatus(scope.row))">
              {{ getPaymentStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="审核备注" width="150">
          <template slot-scope="scope">
            <div v-if="getPaymentStatus(scope.row) === '已拒绝'">
              <div class="rejection-reason">
                <el-tag type="danger" size="mini">拒绝原因</el-tag>
                <span class="reason-text">{{ getRejectionReason(scope.row) }}</span>
              </div>
              <div v-if="getRejectionDetails(scope.row)" class="rejection-details">
                <small>
                  收到: ¥{{ getRejectionReceivedAmount(scope.row) }} | 
                  期望: ¥{{ getRejectionExpectedAmount(scope.row) }}
                </small>
              </div>
            </div>
            <span v-else>{{ getAuditRemark(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="审核人" width="100">
          <template slot-scope="scope">
            <div v-if="getPaymentStatus(scope.row) === '已拒绝'">
              <span class="reject-by">{{ getRejectionBy(scope.row) }}</span>
            </div>
            <span v-else>{{ getAuditorName(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="审核时间" width="150">
          <template slot-scope="scope">
            <div v-if="getPaymentStatus(scope.row) === '已拒绝'">
              <span class="reject-time">{{ formatTime(getRejectionTime(scope.row)) }}</span>
            </div>
            <span v-else>{{ formatTime(getAuditTime(scope.row)) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="提交时间" width="150">
          <template slot-scope="scope">
            <span>{{ formatTime(getCreateTime(scope.row)) }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" width="200" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleView(scope.row)" type="primary" size="mini">查看</el-button>
            <el-button
              v-if="getPaymentStatus(scope.row) === '待确认'"
              @click="handleConfirm(scope.row)"
              type="success"
              size="mini"
            >确认</el-button>
            <el-button
              v-if="getPaymentStatus(scope.row) === '待确认'"
              @click="handleReject(scope.row)"
              type="danger"
              size="mini"
            >拒绝</el-button>
            <el-button
              v-if="getPaymentStatus(scope.row) === '已确认'"
              type="success"
              size="mini"
              disabled
            >已确认</el-button>
            <el-button
              v-if="getPaymentStatus(scope.row) === '已拒绝'"
              type="danger"
              size="mini"
              disabled
            >已拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="computedPagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="computedPagination.count"
          layout="total, sizes, prev, pager, next, jumper"
          :total="computedPagination.total"
        ></el-pagination>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && tableData.length === 0" class="empty-state">
        <el-empty 
          :image="getEmptyImage()"
          :description="getEmptyDescription()"
        >
          <el-button type="primary" @click="handleReset">重置筛选</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog title="支付审核" :visible.sync="auditDialogVisible" width="500px">
      <el-form :model="auditForm" :rules="auditRules" ref="auditForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.action">
            <el-radio label="confirm">确认支付</el-radio>
            <el-radio label="reject">拒绝支付</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付金额" v-if="auditForm.action === 'confirm'">
          <el-input
            v-model.number="auditForm.payAmount"
            type="number"
            placeholder="请输入实际支付金额"
            :min="0.01"
            :step="0.01"
          >
            <template slot="prepend">¥</template>
          </el-input>
          <div style="font-size: 12px; color: #999; margin-top: 5px;">
            订单金额: ¥{{ currentOrderAmount }}
          </div>
        </el-form-item>
        <el-form-item 
          :label="remarkLabel" 
          :rules="auditForm.action === 'reject' ? auditRules.remark : []"
          prop="remark"
        >
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="3"
            :placeholder="remarkLabel"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAudit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="支付详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ currentDetail.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="买家ID">{{ getBuyerId(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="买家昵称">{{ getBuyerNickname(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="卖家ID">{{ getSellerId(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="卖家昵称">{{ getSellerNickname(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="商品标题">{{ getProductTitle(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="商品数量">{{ getProductCount(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="支付金额">
            <div>
              <div>订单金额: ¥{{ getPaymentAmount(currentDetail) }}</div>
              <div v-if="getPayAmount(currentDetail)" style="margin-top: 5px;">
                实际支付: ¥{{ getPayAmount(currentDetail) }}
              </div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentStatusType(getPaymentStatus(currentDetail))">
              {{ getPaymentStatusText(currentDetail) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">{{ getAuditorName(currentDetail) }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ formatTime(getAuditTime(currentDetail)) }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatTime(getCreateTime(currentDetail)) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(getUpdateTime(currentDetail)) }}</el-descriptions-item>
          <el-descriptions-item label="审核备注" :span="2">
            {{ getAuditRemark(currentDetail) }}
          </el-descriptions-item>
          
          <!-- 拒绝记录信息 -->
          <el-descriptions-item 
            v-if="getPaymentStatus(currentDetail) === '已拒绝'" 
            label="拒绝记录" 
            :span="2"
          >
            <div class="rejection-record-detail">
              <div class="rejection-item">
                <strong>拒绝原因：</strong>
                <span>{{ getRejectionReason(currentDetail) }}</span>
              </div>
              <div class="rejection-item">
                <strong>拒绝时间：</strong>
                <span>{{ formatTime(getRejectionTime(currentDetail)) }}</span>
              </div>
              <div class="rejection-item">
                <strong>拒绝人：</strong>
                <span>{{ getRejectionBy(currentDetail) }}</span>
              </div>
              <div class="rejection-item">
                <strong>金额对比：</strong>
                <span>
                  收到: ¥{{ getRejectionReceivedAmount(currentDetail) }} | 
                  期望: ¥{{ getRejectionExpectedAmount(currentDetail) }}
                </span>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 支付凭证信息 -->
        <div v-if="getPaymentProofInfo(currentDetail)" class="payment-proof-section">
          <h4>支付凭证详情</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="支付凭证ID">
              {{ getPaymentProofId(currentDetail) }}
            </el-descriptions-item>
            <el-descriptions-item label="验证状态">
              <el-tag :type="getVerificationStatusType(getVerificationStatus(currentDetail))">
                {{ getVerificationStatusText(getVerificationStatus(currentDetail)) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="是否强制提交">
              <el-tag :type="getForceSubmitType(getForceSubmit(currentDetail))">
                {{ getForceSubmitText(getForceSubmit(currentDetail)) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="人工审核状态">
              <el-tag :type="getManualAuditStatusType(getManualAuditStatus(currentDetail))">
                {{ getManualAuditStatusText(getManualAuditStatus(currentDetail)) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="强制提交原因" :span="2" v-if="getForceSubmitReason(currentDetail)">
              {{ getForceSubmitReason(currentDetail) }}
            </el-descriptions-item>
            <el-descriptions-item label="用户备注" :span="2" v-if="getUserRemark(currentDetail)">
              {{ getUserRemark(currentDetail) }}
            </el-descriptions-item>
            <el-descriptions-item label="审核人" v-if="getAuditorName(currentDetail)">
              {{ getAuditorName(currentDetail) }}
            </el-descriptions-item>
            <el-descriptions-item label="审核时间" v-if="getAuditTime(currentDetail)">
              {{ formatTime(getAuditTime(currentDetail)) }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 账单识别结果 -->
          <div v-if="getBillInfo(currentDetail)" class="bill-recognition-section">
            <h5>账单识别结果</h5>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="收款方名称">
                {{ getBillPayeeName(currentDetail) }}
              </el-descriptions-item>
              <el-descriptions-item label="订单号">
                {{ getBillOrderNumber(currentDetail) }}
              </el-descriptions-item>
              <el-descriptions-item label="支付金额">
                ¥{{ getBillPaymentAmount(currentDetail) }}
              </el-descriptions-item>
              <el-descriptions-item label="支付时间">
                {{ getBillPaymentTime(currentDetail) }}
              </el-descriptions-item>
              <el-descriptions-item label="支付方式">
                {{ getBillPaymentMethod(currentDetail) }}
              </el-descriptions-item>
              <el-descriptions-item label="置信度">
                {{ getBillConfidence(currentDetail) }}%
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 验证结果 -->
          <div v-if="getVerificationInfo(currentDetail)" class="verification-section">
            <h5>验证结果</h5>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="验证状态">
                <el-tag :type="getVerificationStatusType(getVerificationStatus(currentDetail))">
                  {{ getVerificationStatusText(getVerificationStatus(currentDetail)) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="收款方匹配">
                <el-tag :type="getPayeeMatchType(getPayeeMatch(currentDetail))">
                  {{ getPayeeMatchText(getPayeeMatch(currentDetail)) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="订单号重复">
                <el-tag :type="getOrderDuplicateType(getOrderDuplicate(currentDetail))">
                  {{ getOrderDuplicateText(getOrderDuplicate(currentDetail)) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="商户名称">
                {{ getMerchantName(currentDetail) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <div class="payment-section">
          <h4>支付截图/视频</h4>
          <div class="payment-image-wrapper">
            <!-- 视频播放器 -->
            <video 
              v-if="getVideoUrl(currentDetail) && isVideoFile(getVideoUrl(currentDetail))"
              :src="getVideoUrl(currentDetail)"
              controls
              preload="metadata"
              crossorigin="anonymous"
              class="payment-video"
              style="max-height: 80vh; max-width: 90vw; width: auto; height: auto; display: block; margin: 0 auto;"
              @loadstart="onVideoLoadStart"
              @loadedmetadata="onVideoLoadedMetadata"
              @error="onVideoError"
              @canplay="onVideoCanPlay"
            >
              您的浏览器不支持视频播放
            </video>
            <!-- 图片预览 -->
            <el-image
              v-else-if="getPaymentImage(currentDetail) || getVideoUrl(currentDetail)"
              :src="getPaymentImage(currentDetail) || getVideoUrl(currentDetail)"
              :preview-src-list="[getPaymentImage(currentDetail) || getVideoUrl(currentDetail)]"
              fit="contain"
              class="payment-image"
              :style="{ maxHeight: '80vh', maxWidth: '90vw', width: 'auto', height: 'auto', display: 'block', margin: '0 auto' }"
            ></el-image>
            <div v-else style="color: #999; text-align: center; padding: 40px;">
              暂无支付凭证
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPaymentPendingOrders, getPaymentDetail, confirmPayment, rejectPayment, getPaymentStats, batchConfirmPayment, batchRejectPayment } from '@/api/unified-order'

export default {
  name: 'PaymentAuditList',
  data() {
    return {
      loading: false,
      tableData: [],
      selectedRows: [],
      stats: {
        pending: 0,
        confirmed: 0,
        rejected: 0,
        total: 0
      },
      searchForm: {
        status: '',
        keyword: ''
      },
      pagination: {
        page: 1,
        count: 10,
        total: 0
      },
      auditDialogVisible: false,
      detailDialogVisible: false,
      currentDetail: null,
      auditForm: {
        action: 'confirm',
        remark: '',
        payAmount: 0
      },
      currentOrderId: null,
      currentOrderAmount: 0,
      // 强制重新渲染的key
      renderKey: 0,
      auditRules: {
        remark: [
          { required: true, message: '审核备注不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 计算属性确保统计数据响应式更新
    computedStats() {
      return {
        pending: this.stats.pending || 0,
        confirmed: this.stats.confirmed || 0,
        rejected: this.stats.rejected || 0,
        total: this.stats.total || 0
      }
    },
    // 计算属性确保分页数据响应式更新
    computedPagination() {
      return {
        page: this.pagination.page,
        count: this.pagination.count,
        total: this.pagination.total || 0
      }
    },
    // 计算备注字段的标签
    remarkLabel() {
      return this.auditForm.action === 'confirm' ? '审核备注（可选）' : '审核备注（必填）'
    },
    // 计算是否可以批量确认
    canBatchConfirm() {
      return this.selectedRows.length > 0 && this.selectedRows.every(row => this.getPaymentStatus(row) === '待确认')
    },
    // 计算是否可以批量拒绝
    canBatchReject() {
      return this.selectedRows.length > 0 && this.selectedRows.every(row => this.getPaymentStatus(row) === '待确认')
    },
    // 计算当前筛选状态下的订单数量
    filteredOrderCount() {
      if (!this.searchForm.status) {
        return this.tableData.length
      }
      return this.tableData.filter(order => {
        const status = this.getPaymentStatus(order)
        switch (this.searchForm.status) {
          case 'pending':
            return status === '待确认'
          case 'confirmed':
            return status === '已确认'
          case 'rejected':
            return status === '已拒绝'
          default:
            return true
        }
      }).length
    }
  },
  async mounted() {
    await this.loadData()
    await this.loadStats()
  },
  activated() {
    this.loadData()
    this.loadStats()
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.loadData()
      vm.loadStats()
    })
  },
  beforeRouteUpdate(to, from, next) {
    this.loadData()
    this.loadStats()
    next()
  },
  watch: {
    // 监听路由变化
    '$route'(to, from) {
      if (to.path !== from.path) {
        this.debounceRefresh()
      }
    },
    // 监听审核操作类型变化
    'auditForm.action'(newAction) {
      // 当操作类型改变时，清除备注字段的验证状态
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.clearValidate('remark')
        }
      })
    }
  },
  methods: {
    // 加载数据
    async loadData() {
      try {
        this.loading = true
        const params = {
          page: this.pagination.page - 1,
          count: this.pagination.count
        }

        // 根据筛选条件设置参数
        if (this.searchForm.status) {
          params.status = this.searchForm.status
        }

        // 如果有关键词搜索，需要调用不同的API
        if (this.searchForm.keyword && this.searchForm.keyword.trim()) {
          // 关键词搜索时，先获取所有状态的订单，然后在前端筛选
          params.status = '' // 清空状态筛选，获取所有订单
        }

        const response = await getPaymentPendingOrders(params)
        console.log('列表API响应:', response)
        
        let orders = response.items || []
        
        // 如果有关键词，在前端进行筛选
        if (this.searchForm.keyword && this.searchForm.keyword.trim()) {
          const keyword = this.searchForm.keyword.trim().toLowerCase()
          orders = orders.filter(order => {
            const orderNo = (order.orderNo || '').toLowerCase()
            const productTitle = this.getProductTitle(order).toLowerCase()
            return orderNo.includes(keyword) || productTitle.includes(keyword)
          })
        }
        
        this.tableData = orders
        this.pagination.total = orders.length // 前端筛选后的总数
        
        console.log('设置后的tableData长度:', this.tableData.length)
        console.log('设置后的pagination.total:', this.pagination.total)
      } catch (error) {
        this.$message.error('加载数据失败')
        console.error('加载数据失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 加载统计
    async loadStats() {
      try {
        console.log('开始加载统计数据...')
        const response = await getPaymentStats()
        console.log('统计API响应:', response)

        // 直接赋值，因为stats已经在data中初始化了
        if (response) {
          this.stats.pending = response.pending || 0
          this.stats.confirmed = response.confirmed || 0
          this.stats.rejected = response.rejected || 0
          this.stats.total = response.total || 0
        } else {
          this.stats.pending = 0
          this.stats.confirmed = 0
          this.stats.rejected = 0
          this.stats.total = 0
        }

        console.log('设置后的stats:', this.stats)
        // 增加renderKey强制重新渲染
        this.renderKey++
        // 强制更新视图
        this.$nextTick(() => {
          this.$forceUpdate()
          console.log('视图强制更新完成')
        })
      } catch (error) {
        console.error('加载统计失败', error)
        this.stats.pending = 0
        this.stats.confirmed = 0
        this.stats.rejected = 0
        this.stats.total = 0
      }
    },

    // 刷新数据
    async refreshData() {
      // 清空选中的行
      this.selectedRows = []
      // 重新加载数据和统计
      await this.loadData()
      await this.loadStats()
    },

    // 强制刷新
    forceRefresh() {
      this.renderKey++
      this.refreshData()
    },

    // 防抖刷新
    debounceRefresh() {
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer)
      }
      this.refreshTimer = setTimeout(() => {
        this.refreshData()
      }, 300)
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        status: '',
        keyword: ''
      }
      this.handleSearch()
    },

    // 状态筛选变化
    handleStatusChange(value) {
      this.searchForm.status = value
      this.handleSearch()
    },

    // 统计卡片点击处理
    handleStatsCardClick(status) {
      // 如果点击的是当前已选中的状态，则取消筛选
      if (this.searchForm.status === status) {
        this.searchForm.status = ''
      } else {
        this.searchForm.status = status
      }
      this.handleSearch()
    },

    // 分页处理
    handleSizeChange(val) {
      this.pagination.count = val
      this.pagination.page = 1 // 重置到第一页
      this.loadData()
    },

    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadData()
    },

    // 选择处理
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 查看详情
    async handleView(row) {
      try {
        const response = await getPaymentDetail(row.id)
        this.currentDetail = response
        this.detailDialogVisible = true
        this.currentOrderAmount = this.getPaymentAmount(row) // 设置订单金额
      } catch (error) {
        this.$message.error('获取详情失败')
      }
    },

    // 确认支付
    handleConfirm(row) {
      this.currentOrderId = row.id
      this.currentOrderAmount = this.getPaymentAmount(row)
      this.auditForm.action = 'confirm'
      this.auditForm.remark = ''
      this.auditForm.payAmount = this.getPaymentAmount(row)
      this.auditDialogVisible = true
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.clearValidate()
        }
      })
    },

    // 拒绝支付
    handleReject(row) {
      this.currentOrderId = row.id
      this.auditForm.action = 'reject'
      this.auditForm.remark = ''
      this.auditForm.payAmount = 0
      this.auditDialogVisible = true
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.clearValidate()
        }
      })
    },

    // 确认审核
    async confirmAudit() {
      try {
        // 表单验证
        if (this.auditForm.action === 'reject' && !this.auditForm.remark) {
          this.$message.warning('拒绝支付时备注不能为空')
          return
        }
        
        if (this.auditForm.action === 'confirm') {
          if (!this.auditForm.payAmount || this.auditForm.payAmount <= 0) {
            this.$message.warning('请输入有效的支付金额')
            return
          }
          await confirmPayment(this.currentOrderId, {
            remark: this.auditForm.remark || '支付确认通过', // 确认支付时使用默认备注
            pay_amount: this.auditForm.payAmount
          })
          this.$message.success('支付确认成功')
        } else {
          await rejectPayment(this.currentOrderId, {
            remark: this.auditForm.remark
          })
          this.$message.success('支付拒绝成功')
        }
        
        this.auditDialogVisible = false
        await this.loadData()
        await this.loadStats()
        this.selectedRows = []
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    // 批量确认
    async handleBatchConfirm() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要确认的订单')
        return
      }

      try {
        const orderIds = this.selectedRows.map(row => row.id)
        await batchConfirmPayment({
          orderIds: orderIds,
          remark: '批量确认支付 - 系统自动审核通过' // 批量确认时使用更详细的默认备注
        })
        this.$message.success('批量确认成功')
        await this.loadData()
        await this.loadStats()
        this.selectedRows = []
      } catch (error) {
        this.$message.error('批量确认失败')
      }
    },

    // 批量拒绝
    async handleBatchReject() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要拒绝的订单')
        return
      }

      // 弹出输入框让用户输入拒绝原因
      this.$prompt('请输入拒绝原因', '批量拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入拒绝原因（必填）',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '拒绝原因不能为空'
          }
          return true
        }
      }).then(async ({ value }) => {
        try {
          const orderIds = this.selectedRows.map(row => row.id)
          await batchRejectPayment({
            orderIds: orderIds,
            remark: value.trim()
          })
          this.$message.success('批量拒绝成功')
          await this.loadData()
          await this.loadStats()
          this.selectedRows = []
        } catch (error) {
          this.$message.error('批量拒绝失败')
        }
      }).catch(() => {
        // 用户取消输入
      })
    },

    // 获取支付状态类型
    getPaymentStatusType(status) {
      switch (status) {
        case '待确认': return 'warning'
        case '已确认': return 'success'
        case '已拒绝': return 'danger'
        default: return 'info'
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending': return '待确认'
        case 'confirmed': return '已确认'
        case 'rejected': return '已拒绝'
        default: return '全部'
      }
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case 'pending': return 'warning'
        case 'confirmed': return 'success'
        case 'rejected': return 'danger'
        default: return 'info'
      }
    },

    // 清除状态筛选
    clearStatusFilter() {
      this.searchForm.status = ''
      this.handleSearch()
    },

    // 清除关键词筛选
    clearKeywordFilter() {
      this.searchForm.keyword = ''
      this.handleSearch()
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '-'
      const date = new Date(time)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },

    // Helper functions for template access
    getBuyerAvatar(row) {
      return row.buyer_info && row.buyer_info.user_avatar ? row.buyer_info.user_avatar : null
    },
    getBuyerNickname(row) {
      // 优先显示商户名称，如果没有则显示昵称
      if (row.buyer_info && row.buyer_info.merchant_name) {
        return row.buyer_info.merchant_name
      }
      return row.buyer_info && row.buyer_info.user_nickname ? row.buyer_info.user_nickname : '未知用户'
    },
    getBuyerId(row) {
      return row.buyer_info && row.buyer_info.user_id ? row.buyer_info.user_id : 'N/A'
    },
    getSellerAvatar(row) {
      return row.seller_info && row.seller_info.saler_avatar ? row.seller_info.saler_avatar : null
    },
    getSellerNickname(row) {
      // 优先显示商户名称，如果没有则显示昵称
      if (row.seller_info && row.seller_info.merchant_name) {
        return row.seller_info.merchant_name
      }
      return row.seller_info && row.seller_info.saler_nickname ? row.seller_info.saler_nickname : '未知用户'
    },
    getSellerId(row) {
      return row.seller_info && row.seller_info.saler_id ? row.seller_info.saler_id : 'N/A'
    },
    getProductImage(row) {
      return row.product_info && row.product_info.image ? row.product_info.image : null
    },
    getProductTitle(row) {
      return row.product_info && row.product_info.title ? row.product_info.title : '-'
    },
    getProductCount(row) {
      return row.product_info && row.product_info.count ? row.product_info.count : 0
    },
    getPaymentAmount(row) {
      return row.payment_info && row.payment_info.amount ? row.payment_info.amount : 0
    },
    getPayAmount(row) {
      return row.payment_info && row.payment_info.pay_amount ? row.payment_info.pay_amount : null
    },
    getPaymentImage(row) {
      return row.payment_info && row.payment_info.pay_image ? row.payment_info.pay_image : null
    },
    getPaymentStatus(row) {
      return row.payment_info && row.payment_info.payment_status ? row.payment_info.payment_status : '待确认'
    },
    getPaymentStatusText(row) {
      if (row.payment_info && row.payment_info.payment_status_text) {
        return row.payment_info.payment_status_text
      }
      if (row.payment_info && row.payment_info.payment_status) {
        return row.payment_info.payment_status
      }
      return '待确认'
    },
    getAuditRemark(row) {
      return row.audit_info && row.audit_info.remark ? row.audit_info.remark : '-'
    },
    getAuditorName(row) {
      return row.audit_info && row.audit_info.auditor_name ? row.audit_info.auditor_name : '-'
    },
    getAuditTime(row) {
      return row.audit_info && row.audit_info.audit_time ? row.audit_info.audit_time : null
    },
    getCreateTime(row) {
      return row.time_info && row.time_info.create_time ? row.time_info.create_time : null
    },
    getUpdateTime(row) {
      return row.time_info && row.time_info.update_time ? row.time_info.update_time : null
    },
    
    // 拒绝记录相关方法
    getRejectionReason(row) {
      if (row.rejection_info && row.rejection_info.reject_reason) {
        return row.rejection_info.reject_reason
      }
      // 如果没有专门的拒绝记录，尝试从审核信息中获取
      return row.audit_info && row.audit_info.remark ? row.audit_info.remark : '订单被拒绝'
    },
    
    getRejectionTime(row) {
      return row.rejection_info && row.rejection_info.reject_time ? row.rejection_info.reject_time : null
    },
    
    getRejectionBy(row) {
      return row.rejection_info && row.rejection_info.reject_by_name ? row.rejection_info.reject_by_name : '系统'
    },
    
    getRejectionReceivedAmount(row) {
      if (row.rejection_info && row.rejection_info.received_amount) {
        return row.rejection_info.received_amount
      }
      // 如果没有专门的拒绝记录，使用支付金额
      return row.payment_info && row.payment_info.pay_amount ? row.payment_info.pay_amount : '-'
    },
    
    getRejectionExpectedAmount(row) {
      if (row.rejection_info && row.rejection_info.expected_amount) {
        return row.rejection_info.expected_amount
      }
      // 如果没有专门的拒绝记录，使用订单金额
      return row.payment_info && row.payment_info.amount ? row.payment_info.amount : '-'
    },
    
    getRejectionDetails(row) {
      return row.rejection_info && (row.rejection_info.received_amount || row.rejection_info.expected_amount)
    },
    
    // 获取空状态图片
    getEmptyImage() {
      return 'https://cube.elemecdn.com/0/88/03b0d60f60d1a623e940083c0008png.png'
    },
    // 获取空状态描述
    getEmptyDescription() {
      return '暂无符合条件的支付审核记录'
    },

    // 支付凭证相关方法
    getPaymentProofInfo(row) {
      return row.payment_proof_info || null
    },

    getPaymentProofId(row) {
      return row.payment_proof_info && row.payment_proof_info.payment_proof_id ? row.payment_proof_info.payment_proof_id : '-'
    },

    getVideoUrl(row) {
      return row.payment_proof_info && row.payment_proof_info.video_url ? row.payment_proof_info.video_url : null
    },

    getVerificationStatus(row) {
      return row.payment_proof_info && row.payment_proof_info.verification_status ? row.payment_proof_info.verification_status : 'unknown'
    },

    getForceSubmit(row) {
      return row.payment_proof_info && row.payment_proof_info.force_submit ? row.payment_proof_info.force_submit : false
    },

    getForceSubmitReason(row) {
      return row.payment_proof_info && row.payment_proof_info.force_submit_reason ? row.payment_proof_info.force_submit_reason : null
    },

    getUserRemark(row) {
      return row.payment_proof_info && row.payment_proof_info.user_remark ? row.payment_proof_info.user_remark : null
    },

    getManualAuditStatus(row) {
      return row.payment_proof_info && row.payment_proof_info.manual_audit_status ? row.payment_proof_info.manual_audit_status : null
    },

    getManualAuditRemark(row) {
      return row.payment_proof_info && row.payment_proof_info.manual_audit_remark ? row.payment_proof_info.manual_audit_remark : null
    },

    getAuditorName(row) {
      return row.payment_proof_info && row.payment_proof_info.auditor_name ? row.payment_proof_info.auditor_name : null
    },

    getAuditTime(row) {
      return row.payment_proof_info && row.payment_proof_info.audit_time ? row.payment_proof_info.audit_time : null
    },

    // 账单识别结果相关方法
    getBillInfo(row) {
      return row.payment_proof_info && row.payment_proof_info.verification_result && row.payment_proof_info.verification_result.bill_info ? row.payment_proof_info.verification_result.bill_info : null
    },

    getBillPayeeName(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.payee_name ? billInfo.payee_name : '未识别'
    },

    getBillOrderNumber(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.order_number ? billInfo.order_number : '未知订单号'
    },

    getBillPaymentAmount(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.payment_amount ? billInfo.payment_amount : 0
    },

    getBillPaymentTime(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.payment_time ? billInfo.payment_time : '未知时间'
    },

    getBillPaymentMethod(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.payment_method ? billInfo.payment_method : '未知支付方式'
    },

    getBillConfidence(row) {
      const billInfo = this.getBillInfo(row)
      return billInfo && billInfo.confidence ? Math.round(billInfo.confidence * 100) : 0
    },

    // 验证结果相关方法
    getVerificationInfo(row) {
      return row.payment_proof_info && row.payment_proof_info.verification_result && row.payment_proof_info.verification_result.verification ? row.payment_proof_info.verification_result.verification : null
    },

    getPayeeMatch(row) {
      const verification = this.getVerificationInfo(row)
      return verification && verification.payee_match !== undefined ? verification.payee_match : null
    },

    getOrderDuplicate(row) {
      const verification = this.getVerificationInfo(row)
      return verification && verification.order_duplicate !== undefined ? verification.order_duplicate : null
    },

    getMerchantName(row) {
      const verification = this.getVerificationInfo(row)
      return verification && verification.merchant_name ? verification.merchant_name : '未知商户'
    },

    // 状态标签类型和文本方法
    getVerificationStatusType(status) {
      switch (status) {
        case 'success': return 'success'
        case 'failed': return 'danger'
        case 'manual_review': return 'warning'
        default: return 'info'
      }
    },

    getVerificationStatusText(status) {
      switch (status) {
        case 'success': return '验证成功'
        case 'failed': return '验证失败'
        case 'manual_review': return '人工审核中'
        default: return '未知状态'
      }
    },

    getForceSubmitType(forceSubmit) {
      return forceSubmit ? 'warning' : 'info'
    },

    getForceSubmitText(forceSubmit) {
      return forceSubmit ? '是' : '否'
    },

    getManualAuditStatusType(status) {
      switch (status) {
        case 'pending': return 'warning'
        case 'approved': return 'success'
        case 'rejected': return 'danger'
        default: return 'info'
      }
    },

    getManualAuditStatusText(status) {
      switch (status) {
        case 'pending': return '待审核'
        case 'approved': return '已通过'
        case 'rejected': return '已拒绝'
        default: return '未审核'
      }
    },

    getPayeeMatchType(match) {
      if (match === null) return 'info'
      return match ? 'success' : 'danger'
    },

    getPayeeMatchText(match) {
      if (match === null) return '未验证'
      return match ? '匹配' : '不匹配'
    },

    getOrderDuplicateType(duplicate) {
      if (duplicate === null) return 'info'
      return duplicate ? 'danger' : 'success'
    },

    getOrderDuplicateText(duplicate) {
      if (duplicate === null) return '未验证'
      return duplicate ? '重复' : '不重复'
    },

    // 判断是否为视频文件
    isVideoFile(url) {
      if (!url) return false
      const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv']
      return videoExtensions.some(ext => url.toLowerCase().includes(ext))
    },

    // 视频事件处理方法
    onVideoLoadStart(event) {
      console.log('视频开始加载:', event.target.src)
    },

    onVideoLoadedMetadata(event) {
      console.log('视频元数据加载完成:', {
        duration: event.target.duration,
        videoWidth: event.target.videoWidth,
        videoHeight: event.target.videoHeight,
        readyState: event.target.readyState
      })
    },

    onVideoError(event) {
      console.error('视频加载错误:', {
        error: event.target.error,
        networkState: event.target.networkState,
        readyState: event.target.readyState,
        src: event.target.src
      })
      this.$message.error('视频加载失败，请检查网络连接或视频文件')
    },

    onVideoCanPlay(event) {
      console.log('视频可以播放:', {
        duration: event.target.duration,
        videoWidth: event.target.videoWidth,
        videoHeight: event.target.videoHeight
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.payment-audit-page {
  padding: 16px 16px 24px; // 上下左右内边距，避免贴边
}

.page-header {
  margin-bottom: 16px;
  .page-title {
    font-size: 18px;
    font-weight: 600;
    line-height: 1.2;
  }
  .page-subtitle {
    margin-top: 4px;
    color: #909399;
    font-size: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;
  margin-top: 4px;

  .stats-card {
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      border-color: #409EFF;
    }

    &.stats-card-active {
      border-color: #409EFF;
      background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
      color: white;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

      .stats-content {
        .stats-number {
          color: white;
        }

        .stats-label {
          color: white;
        }
      }
    }

    .stats-content {
      text-align: center;

      .stats-number {
        font-size: 24px;
        font-weight: bold;
        color: #409EFF;
        margin-bottom: 8px;
        transition: color 0.3s ease;
      }

      .stats-label {
        font-size: 14px;
        color: #666;
        transition: color 0.3s ease;
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;

  .search-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .table-title {
      font-size: 16px;
      font-weight: bold;
      .order-count {
        margin-left: 8px;
        font-size: 14px;
        color: #909399;
      }
    }

    .table-actions {
      .el-button {
        margin-left: 10px;
      }
    }
  }
}

.user-info {
  display: flex;
  align-items: center;

  .user-name {
    margin-left: 8px;
    font-weight: 500;
  }
}

.product-info {
  display: flex;
  align-items: center;

  .product-title {
    font-weight: 500;
    margin-bottom: 4px;
  }
}

.price {
  font-weight: bold;
  color: #E6A23C;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  
  .el-empty {
    .el-empty__description {
      color: #909399;
      font-size: 14px;
    }
  }
}

.filter-status {
  margin-top: 10px;
  .el-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
}

.rejection-reason {
  margin-bottom: 5px;
  
  .reason-text {
    margin-left: 8px;
    color: #f56c6c;
    font-weight: 500;
  }
}

.rejection-details {
  color: #909399;
  font-size: 12px;
}

.reject-by {
  color: #f56c6c;
  font-weight: 500;
}

.reject-time {
  color: #f56c6c;
  font-weight: 500;
}

.rejection-record-detail {
  .rejection-item {
    margin-bottom: 8px;
    
    strong {
      color: #333;
      margin-right: 8px;
    }
    
    span {
      color: #666;
    }
  }
}

.detail-content {
  .payment-proof-section {
    margin-top: 20px;
    margin-bottom: 20px;

    h4 {
      margin-bottom: 15px;
      color: #333;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 8px;
    }

    h5 {
      margin: 20px 0 15px 0;
      color: #666;
      font-size: 16px;
    }

    .bill-recognition-section,
    .verification-section {
      margin-top: 15px;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 6px;
      border-left: 4px solid #409EFF;
    }
  }

  .payment-section {
    margin-top: 20px;

    h4 {
      margin-bottom: 15px;
      color: #333;
    }

    .payment-image-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;

      .payment-image {
        max-height: 70vh; /* 限制最大高度为可视区域的70% */
        max-width: 90%;
        object-fit: contain;
      }

      .payment-video {
        max-height: 70vh;
        max-width: 90%;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }

    /* 修正 Element UI 内部 img 默认宽高为100%导致拉伸的问题 */
    ::v-deep .payment-image .el-image__inner {
      width: auto !important;
      height: auto !important;
      max-width: 100%;
      max-height: 70vh;
      object-fit: contain !important;
      display: block;
      margin: 0 auto;
    }
  }
}
</style>

<style>
/* 非 scoped，全局修正 Element UI 内部 img 拉伸问题 */
.payment-image .el-image__inner {
  width: auto !important;
  height: auto !important;
  max-width: 90vw;
  max-height: 80vh;
  object-fit: contain !important;
  display: block;
  margin: 0 auto;
}
</style>
